package com.wwj.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Set;

public class HttpUtils {

    //定义全局的请求头版本号
    public static BasicHeader lemonHeader = new BasicHeader("X-Lemonban-Media-Type", "lemonban.v2");


    /**请求接口
     * @param url
     * @param params
     * @param type
     * @param ContentType
     * @return
     */
    public static String call(String url,String params,String type,String ContentType){
        //json格式

        System.out.println("----开始请求接口=====");
        if ("json".equalsIgnoreCase(ContentType)){
            if("get".equalsIgnoreCase(type)){
              return   HttpUtils.testGetJson(url,params);
            }else if("post".equalsIgnoreCase(type)){
               return HttpUtils.testPostjson(url,params);

            }
            //form格式
        }else if("form".equalsIgnoreCase(ContentType)){
            //params是json格式，可以通过fastjson转换为Map对象，（key,value）,
            // 再将map对象转换为key,
            String keyValueParams = jsonToKeyValue(params);
            System.out.println(keyValueParams);
           return HttpUtils.testPostForm(url,params);


        }
        return "";
    }


    public static String jsonToKeyValue(String params) {

        //params是json格式，可以通过fastjson转换为Map对象，（key,value）,
        // 再将map对象转换为key,value格式

        //1.params转换为Map对象
        HashMap<String, String> map = JSONObject.parseObject(params, HashMap.class);
        //2.Map对象转换为对应的字符串
        String keyValueParams = "";
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            String value = map.get(key);
            //1.keyValueParams += key + "=" + value + "&";
            if (keyValueParams.length()>0){
                keyValueParams+="&";
            }

            keyValueParams+=key+"="+value;

        }

        //keyValueParams = keyValueParams.substring(0, keyValueParams.length() - 1);
        return keyValueParams;
    }



    public static String testGetJson(String url,String params) {
        try {

            //1.创建一个request,携带了method和URL(get请求直接拼接在url)
//        String url = "http://api.lemonban.com/futureloan/loans";
            HttpGet get = new HttpGet(url);
            //添加请求头
            get.addHeader(lemonHeader);
            //2.但是请求不能自己发送，需要有客户端，创建一个发送请求的客户端,httpclients是httpclient的工具类
            CloseableHttpClient client = HttpClients.createDefault();
            //3.发送get请求,并返回http响应
            CloseableHttpResponse response  = client.execute(get);
            ;

            //4.接收响应，response是整个响应对象(body,header,statuscode)，是个数组
            //4.1获取所有响应头
            Header[] allHeaders = response.getAllHeaders();
//        //4.2获取状态码
//        int statusCode = response.getStatusLine().getStatusCode();
            //4.3获取响应体
            HttpEntity entity = response.getEntity();

            //5. 格式化响应体
            String body = EntityUtils.toString(entity);
            //6.输出响应
            for (Header header : allHeaders) {
                System.out.println(header);
            }

//        System.out.println(allHeaders);
//        System.out.println(statusCode);
            System.out.println(body);
            return body;

        } catch (IOException e) {
            e.printStackTrace();
        }

        return "";
    }

    public static String testPostjson(String url,String params) {
        try {

//
            HttpPost post = new HttpPost(url);
            //添加请求头
            post.addHeader(lemonHeader);
            post.addHeader("Content-Type", "application/json");

            //添加请求体
            StringEntity requestEntity = new StringEntity(params,"utf-8");

            post.setEntity(requestEntity);
            //添加请求头鉴权
            AuthenticationUtils.addToken(post);
            System.out.println("post请求体:"+post);

            //2.但是请求不能自己发送，需要有客户端，创建一个发送请求的客户端,httpclients是httpclient的工具类


            CloseableHttpClient client = HttpClients.createDefault();
            //3.发送get请求,并返回http响应
            CloseableHttpResponse response = client.execute(post);
            //4.接收响应，response是整个响应对象(body,header,statuscode)，是个数组
            //4.1获取所有响应头
            Header[] allHeaders = response.getAllHeaders();
//        //4.2获取状态码
           int statusCode = response.getStatusLine().getStatusCode();
            //4.3获取响应体
            HttpEntity entity = response.getEntity();

            //5. 格式化响应体
            String body = EntityUtils.toString(entity);
            //6.输出响应
            for (Header header : allHeaders) {
                System.out.println(header);
            }

        System.out.println();
        System.out.println("响应状态码是："+statusCode);
        System.out.println("响应体是："+body);

        //token存储
            AuthenticationUtils.storeToken(body);
            return body;


        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";

    }


    //form表单格式
    public static String testPostForm(String url,String params) {
        try {

//
            HttpPost post = new HttpPost(url);
            //添加请求头
            post.addHeader(lemonHeader);
            post.addHeader("Content-Type", "application/x-www-form-urlencoded");

            //添加请求体
            StringEntity requestEntity = new StringEntity(params,"utf-8");

            post.setEntity(requestEntity);

            //添加请求头鉴权
            AuthenticationUtils.addToken(post);
            System.out.println("post请求体:"+post);

            //2.但是请求不能自己发送，需要有客户端，创建一个发送请求的客户端,httpclients是httpclient的工具类


            CloseableHttpClient client = HttpClients.createDefault();
            //3.发送get请求,并返回http响应
            CloseableHttpResponse response = client.execute(post);
            //4.接收响应，response是整个响应对象(body,header,statuscode)，是个数组
            //4.1获取所有响应头
            Header[] allHeaders = response.getAllHeaders();
//        //4.2获取状态码
//        int statusCode = response.getStatusLine().getStatusCode();
            //4.3获取响应体
            HttpEntity entity = response.getEntity();

            //5. 格式化响应体
            String body = EntityUtils.toString(entity);
            //6.输出响应
            for (Header header : allHeaders) {
                System.out.println(header);
            }

//        System.out.println(allHeaders);
//        System.out.println(statusCode);
            System.out.println(body);
            return body;


        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";

    }


    public static void main(String[] args) {
//        String url1 = "http://api.lemonban.com/futureloan/loans";
//        String params1 = "";
//        HttpUtils.testGetJson(url1,params1);
//
//        String url2 = "http://api.lemonban.com/futureloan/member/login";
//        String params2 = "{\n" +
//                "\t\"mobile_phone\":\"18311447530\",\n" +
//                "\t\"pwd\":\"12345678\"\n" +
//                "}";
//        HttpUtils.testPostjson(url2,params2);



        String url3 = "http://test.lemonban.com/futureloan/mvc/api/member/register";
        //form表单格式的参数，如果为JSon格式的话当前无法进行解析，因为请求头已经定义了
        String params3 ="mobilephone=18311447530&pwd=123456789";
        HttpUtils.testPostForm(url3,params3);


    }



}
